package com.aruba.lifecycle;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/**
 * Created by aruba on 2021/9/9.
 */
public class MyLocationObserver implements LifecycleObserver {

    private Context context;
    private LocationManager locationManager;
    private MyLocation listener;

    public MyLocationObserver(Context context) {
        this.context = context;
    }

    /**
     * 开启gps
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void startGetLocation() {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        listener = new MyLocation();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300, 1, listener);
    }

    /**
     * 关闭gps
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void stopGetLocation() {
        locationManager.removeUpdates(listener);
    }

    static class MyLocation implements LocationListener {

        private static final String TAG = MyLocation.class.getSimpleName();

        @Override
        public void onLocationChanged(@NonNull Location location) {
            Log.i(TAG, location.toString());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            
        }

        @Override
        public void onProviderEnabled(@NonNull String provider) {

        }

        @Override
        public void onProviderDisabled(@NonNull String provider) {

        }
    }
}
